package game.module.ddz.processor;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.ddz.bean.DdzRound;
import game.module.ddz.logic.DdzDataManager;
import game.module.user.bean.PlayerBean;
import game.module.user.logic.RoomDataManager;
import game.session.SessionManager;
import lion.common.ArrayUtility;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageDdz.C2SDdzBackRoom;
import lua.LuaMessageDdz.JiaBeiInfo;
import lua.LuaMessageDdz.MemberInfo;
import lua.LuaMessageDdz.PushDdzConnectRoom;
import lua.LuaMessageDdz.S2CDdzBackRoom;
import lua.LuaMessageLogin.S2ErrorCode;

@MsgCodeAnn(msgcode = C2SDdzBackRoom.id, accessLimit = 1000)
public class DdzBackRoomProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(DdzBackRoomProcessor.class);

	@Override
	public void process(PlayingRole playingRole, RequestMessageRaw request) throws Exception {
		int playerId = playingRole.getId();
		logger.info("ddz back room,playerId={}", playerId);
		// 房间是否存在
		DdzRound ddzRound = DdzDataManager.getInstance().getDdzRoom(playerId);
		if (ddzRound == null) {
			S2ErrorCode respMsg = new S2ErrorCode(201);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		// do
		S2CDdzBackRoom respMsg = new S2CDdzBackRoom();
		respMsg.room_id = ddzRound.getRoomUuid();
		respMsg.round_count = ddzRound.getRoundSum();
		respMsg.anti_cheet = (byte)1;
		respMsg.jiao_or_qiang = ddzRound.getJiaoFenOrQiang();
		respMsg.current_round = ddzRound.getRoundCount().shortValue();
		respMsg.members = new MemberInfo[ddzRound.getPlayerIds().size()];
		List<Integer> playerIdList = ddzRound.getPlayerIds();
		int i = 0;
		for (Integer aPlayerId : playerIdList) {
			PlayerBean poc = RoomDataManager.getInstance().getPlayerBean(aPlayerId);
			respMsg.members[i++] = new MemberInfo(aPlayerId, poc.getHeadimg(), 1, poc.getSex().shortValue(),
					poc.getName());
		}
		int myIndex = playerIdList.indexOf(playerId);
		respMsg.my_cards = ArrayUtility.toByteArray(ddzRound.getCards().get(myIndex));
		if (ddzRound.isJiaBei()) {
			respMsg.di_cards = ArrayUtility.toByteArray(ddzRound.getDi());
		}
		respMsg.left_card_count = new byte[playerIdList.size()];
		i = 0;
		List<List<Byte>> playerCards = ddzRound.getCards();
		for (List<Byte> list : playerCards) {
			respMsg.left_card_count[i++] = (byte) list.size();
		}
		Integer JiaoDiZhuIndex = ddzRound.getJiaoDiZhuIndex();
		respMsg.jiao_dizhu_index = JiaoDiZhuIndex != null ? JiaoDiZhuIndex.byteValue() : -1;
		Short lastJiaoScore = ddzRound.getLastJiaoScore();
		respMsg.jiao_dizhu_score = lastJiaoScore != null ? lastJiaoScore.byteValue() : -1;
		Integer DiZhuIndex = ddzRound.getDiZhuIndex();
		respMsg.zhuangjia_index = DiZhuIndex != null ? DiZhuIndex.byteValue() : -1;
		//抢地主
		Integer qiangDiZhuIndex = ddzRound.getQiangDiZhuIndex();
		respMsg.qiang_dizhu_index = qiangDiZhuIndex != null ? qiangDiZhuIndex.byteValue() : -1;
		// 加倍列表
		Map<Integer, Integer> jiaBeiMap = ddzRound.getJiaBeiMap();
		if (jiaBeiMap != null) {
			respMsg.jiabei_info = new JiaBeiInfo[jiaBeiMap.size()];
			int k = 0;
			for (Map.Entry<Integer, Integer> jiaBeiEntity : jiaBeiMap.entrySet()) {
				respMsg.jiabei_info[k++] = new JiaBeiInfo(jiaBeiEntity.getKey().byteValue(),
						jiaBeiEntity.getValue().byteValue());
			}
		}
		Integer ChuPaiIndex = ddzRound.getChuPaiIndex();
		respMsg.chupai_player_index = ChuPaiIndex != null ? ChuPaiIndex.byteValue() : -1;
		Integer ValidChupaiIndex = ddzRound.getValidChupaiIndex();
		respMsg.valid_chupai_index = ValidChupaiIndex != null ? ValidChupaiIndex.byteValue() : -1;
		byte[] pai_content = ddzRound.getValid_chuPai();
		respMsg.chupai_card = pai_content;
		
		respMsg.create_time = ddzRound.getCreate_time();
		//房间服务器连上的信息
		Set<Integer> connectedPlayerSet = ddzRound.getConnectedPlayerIndexSet();
		if(connectedPlayerSet == null) {
			connectedPlayerSet = new HashSet<>();
			ddzRound.setConnectedPlayerIndexSet(connectedPlayerSet);
		}
		connectedPlayerSet.add(myIndex);
		byte[] connectedPlayerIndexs = ArrayUtility.toByteArray(connectedPlayerSet);
		respMsg.connected_player_indexs = connectedPlayerIndexs;
		// send
		playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
		// push
		PushDdzConnectRoom pushMsg = new PushDdzConnectRoom((byte) myIndex);
		List<Integer> playerIds = ddzRound.getPlayerIds();
		for (Integer aPlayerId : playerIds) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushMsg.build(pr.alloc()));
			}
		}
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {

	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {

	}

}
